package org.zhangsh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.zhangsh.socket.HostInfo;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-27
 */
public class TimerServerHandler extends ChannelInboundHandlerAdapter {

    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "开始读...");

        /*ByteBuf buf = (ByteBuf) msg;
        byte[] request = new byte[buf.readableBytes()];
        buf.readBytes(request);
        String body = new String(request, StandardCharsets.UTF_8);*/
        String body = (String) msg;
        // 接收的消息去除换行分隔
//        body = body.substring(0, request.length-HostInfo.SEPARATOR.length());
        System.out.println(HostInfo.THREAD_NAME + "服务器接收数据：" + body);

        /*String currentTime = HostInfo.QUERY_TIME.equalsIgnoreCase(body) ?
                new Date(System.currentTimeMillis()).toString() : HostInfo.BAD_ORDER;

        // 增加换行
        currentTime += HostInfo.SEPARATOR + "\0";

        ByteBuf response = Unpooled.copiedBuffer(currentTime.getBytes());
        System.out.println(HostInfo.THREAD_NAME + "响应数据： " + currentTime);
        // 返回客户端
        ctx.writeAndFlush(response);*/

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "读完成");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println(HostInfo.THREAD_NAME + "异常");
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            System.out.println("timeout...");
            ctx.close();
        }
    }
}
